import React, { useState } from 'react';
import {
  Card,
  Table,
  Tag,
  Space,
  Button,
  Typography,
  Modal,
  Form,
  Input,
  Select,
  Row,
  Col,
  Statistic,
  message,
  Tabs,
  Badge,
  Descriptions,
  InputNumber,
  DatePicker,
  Tooltip
} from 'antd';
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  EyeOutlined,
  FileSearchOutlined,
  ClockCircleOutlined,
  LikeOutlined,
  DislikeOutlined
} from '@ant-design/icons';

const { Title, Paragraph, Text } = Typography;
const { Option } = Select;
const { TextArea } = Input;
const { TabPane } = Tabs;

const mockPortfolios = [
  {
    id: 'P001',
    name: '稳健增长FOF组合',
    type: 'FOF组合',
    creator: '王牌投顾团队',
    submitTime: '2024-01-20 10:30',
    status: 'pending',
    riskLevel: 'medium',
    description: '旨在通过精选一篮子基金，实现长期稳健的资本增值。',
    targetReturn: 12,
    maxDrawdown: -8,
    benchmark: '沪深300',
    components: [
      { code: '000001', name: '华夏成长混合', weight: 30 },
      { code: '000002', name: '易方达消费行业', weight: 30 },
      { code: '000006', name: '广发稳健增长', weight: 40 },
    ]
  },
  {
    id: 'P004',
    name: '新能源主题投资组合',
    type: '主题组合',
    creator: '新能源研究团队',
    submitTime: '2024-01-21 14:20',
    status: 'pending',
    riskLevel: 'high',
    description: '聚焦新能源产业链，包括光伏、风电、储能等细分领域，把握碳中和政策红利。',
    targetReturn: 20,
    maxDrawdown: -12,
    benchmark: '中证新能源指数',
    components: [
      { code: '159915', name: '创业板ETF', weight: 40 },
      { code: '512660', name: '军工ETF', weight: 30 },
      { code: '515030', name: '新能源车ETF', weight: 30 },
    ]
  },
  {
    id: 'P002',
    name: '全球科技先锋策略',
    type: '策略组合',
    creator: '海外投资部',
    submitTime: '2025-06-22 15:00',
    status: 'approved',
    riskLevel: 'high',
    description: '聚焦全球领先的科技公司，捕捉创新带来的高成长机会。',
    targetReturn: 25,
    maxDrawdown: -15,
    benchmark: '纳斯达克100',
    components: [
      { code: '513100', name: '纳斯达克100ETF', weight: 70 },
      { code: '159915', name: '创业板ETF', weight: 30 },
    ]
  },
  {
    id: 'P003',
    name: '大类资产轮动',
    type: '策略组合',
    creator: '量化策略组',
    submitTime: '2025-06-23 09:45',
    status: 'rejected',
    riskLevel: 'medium',
    description: '通过宏观经济指标判断资产类别强弱，进行动态轮动配置。',
    targetReturn: 15,
    maxDrawdown: -10,
    benchmark: '中证800',
    components: [
      { code: '510300', name: '沪深300ETF', weight: 50 },
      { code: '511010', name: '国债ETF', weight: 50 },
    ],
    rejectionReason: '回测数据显示，在市场快速切换时，策略延迟较大，建议优化信号捕捉模块。'
  },
];

const PortfolioAudit = () => {
  // 强制清除localStorage，使用mock数据
  localStorage.removeItem('portfolioAuditData');
  const [portfolios, setPortfolios] = useState(mockPortfolios);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedPortfolio, setSelectedPortfolio] = useState(null);
  const [form] = Form.useForm();

  const handleOpenModal = (record) => {
    setSelectedPortfolio(record);
    setIsModalVisible(true);
  };

  const handleAudit = (action) => {
    form.validateFields().then(values => {
      const newStatus = action === 'approve' ? 'approved' : 'rejected';
      const rejectionReason = action === 'reject' ? values.rejectionReason : undefined;
      const newPortfolios = portfolios.map(p =>
        p.id === selectedPortfolio.id
          ? { ...p, status: newStatus, rejectionReason }
          : p
      );
      setPortfolios(newPortfolios);
      // 审核后写入localStorage
      localStorage.setItem('portfolioAuditData', JSON.stringify(newPortfolios));
      message.success(`组合 "${selectedPortfolio.name}" 已${newStatus === 'approved' ? '通过' : '驳回'}`);
      setIsModalVisible(false);
      form.resetFields();
    }).catch(info => {
      console.log('Validate Failed:', info);
    });
  };

  const getStatusTag = (status) => {
    switch (status) {
      case 'pending':
        return <Tag icon={<ClockCircleOutlined />} color="processing">待审核</Tag>;
      case 'approved':
        return <Tag icon={<CheckCircleOutlined />} color="success">已上架</Tag>;
      case 'rejected':
        return <Tag icon={<CloseCircleOutlined />} color="error">已驳回</Tag>;
      default:
        return <Tag>{status}</Tag>;
    }
  };

  const columns = [
    { title: '组合ID', dataIndex: 'id', key: 'id', width: 100 },
    { title: '组合名称', dataIndex: 'name', key: 'name', width: 200 },
    { title: '类型', dataIndex: 'type', key: 'type', width: 120, render: (t) => <Tag color="blue">{t}</Tag> },
    { title: '创建方', dataIndex: 'creator', key: 'creator', width: 150 },
    { title: '提交时间', dataIndex: 'submitTime', key: 'submitTime', width: 180 },
    { title: '状态', dataIndex: 'status', key: 'status', width: 120, render: getStatusTag },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => (
        <Button
          type="primary"
          icon={<FileSearchOutlined />}
          onClick={() => handleOpenModal(record)}
          disabled={record.status !== 'pending'}
        >
          审核
        </Button>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Title level={3}>策略组合上架审核</Title>
      <Paragraph type="secondary">
        投资决策委员会对提交的策略组合、FOF组合等产品进行审核，通过后即可上架至产品专区。
      </Paragraph>

      <Card>
        <Table
          dataSource={portfolios}
          columns={columns}
          rowKey="id"
          pagination={{ pageSize: 10 }}
        />
      </Card>

      <Modal
        title="组合产品审核"
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        width={900}
        footer={[
          <Button key="back" onClick={() => setIsModalVisible(false)}>
            取消
          </Button>,
          <Button key="reject" type="primary" danger icon={<DislikeOutlined />} onClick={() => handleAudit('reject')}>
            驳回
          </Button>,
          <Button key="approve" type="primary" icon={<LikeOutlined />} onClick={() => handleAudit('approve')}>
            审核通过
          </Button>,
        ]}
      >
        {selectedPortfolio && (
          <Tabs defaultActiveKey="1">
            <TabPane tab="基本信息" key="1">
              <Descriptions bordered column={2}>
                <Descriptions.Item label="组合ID">{selectedPortfolio.id}</Descriptions.Item>
                <Descriptions.Item label="组合名称">{selectedPortfolio.name}</Descriptions.Item>
                <Descriptions.Item label="类型">{selectedPortfolio.type}</Descriptions.Item>
                <Descriptions.Item label="风险等级">
                  <Tag color={selectedPortfolio.riskLevel === 'high' ? 'red' : 'orange'}>{selectedPortfolio.riskLevel}</Tag>
                </Descriptions.Item>
                <Descriptions.Item label="创建方" span={2}>{selectedPortfolio.creator}</Descriptions.Item>
                <Descriptions.Item label="目标年化收益">{selectedPortfolio.targetReturn}%</Descriptions.Item>
                <Descriptions.Item label="最大回撤容忍度">{selectedPortfolio.maxDrawdown}%</Descriptions.Item>
                <Descriptions.Item label="业绩基准">{selectedPortfolio.benchmark}</Descriptions.Item>
                <Descriptions.Item label="提交时间">{selectedPortfolio.submitTime}</Descriptions.Item>
                <Descriptions.Item label="组合描述" span={2}>{selectedPortfolio.description}</Descriptions.Item>
              </Descriptions>
            </TabPane>
            <TabPane tab="成分列表" key="2">
              <Table
                dataSource={selectedPortfolio.components}
                columns={[
                  { title: '基金代码', dataIndex: 'code', key: 'code' },
                  { title: '基金名称', dataIndex: 'name', key: 'name' },
                  { title: '配置权重(%)', dataIndex: 'weight', key: 'weight' },
                ]}
                rowKey="code"
                pagination={false}
                size="small"
              />
            </TabPane>
            <TabPane tab="审核意见" key="3">
              <Form form={form} layout="vertical">
                <Form.Item
                  name="rejectionReason"
                  label="驳回理由（如果驳回，此项必填）"
                  rules={[{
                    required: true,
                    message: '请输入驳回理由',
                  }]}
                >
                  <TextArea rows={4} placeholder="请详细说明驳回原因，例如数据问题、逻辑缺陷、风险过高等。" />
                </Form.Item>
              </Form>
            </TabPane>
          </Tabs>
        )}
      </Modal>
    </div>
  );
};

export default PortfolioAudit; 